#!/bin/bash

do_usage() {
    echo "$1 list"
    echo "$1 get"
    echo "$1 set {auto|<device>}"
    echo "$1 list-profiles"
    echo "$1 get-profile"
    echo "$1 set-profile {auto|<profile>}"
    echo "$1 getSystemVolume"
    echo "$1 setSystemVolume {mute|unmute|mute-toggle|[+-]<0...100>}"
    echo "$1 getSystemMute"
    echo "$1 test"
}

# Export XDG for PW
export XDG_RUNTIME_DIR=/var/run

# Set variables
MAX_VOLUME="$(/usr/bin/batocera-settings-get audio.volume.boost)" || MAX_VOLUME=100
DEFAULT_SINK=$(LC_ALL=C pactl info | grep -E '^Default Sink: ' | sed -e s+"^Default Sink: "+""+ | head -1)
DETECT_VOLUME=$(LC_ALL=C pactl list sinks-raw | grep -E '^[^ ]* name="'"${DEFAULT_SINK}"'"' | sed -e s+"^.* volume=\"\([0-9]*\)\" .*$"+'\1'+)

ACTION="$1"

case "${ACTION}" in
    list)
        printf "auto\tauto\n"
        LC_ALL=C pactl list sinks-raw | sed -e s+"^sink=\"[0-9]*\" name=\"\([^ ]*\)\" .* description=\"\(.*\)\"$"+"\1\t\2"+
        ;;

    get)
        /usr/bin/batocera-settings-get audio.device
        ;;

    set)
        MODE="$2"
        case "${MODE}" in
            auto)
                BT_SINK=$(LC_ALL=C pactl list short sinks | grep bluez_output | awk '{print $2}' | head -n1)
                if [ -n "$BT_SINK" ]; then
                    MODE="$BT_SINK"
                    LC_ALL=C pactl set-default-sink "${MODE}" || exit 1
                else
                    ARCH=$(cat /usr/share/batocera/batocera.arch)
                    BOARD=$(cat /boot/boot/batocera.board)

                    case "${ARCH}" in
                        "rk3399")
                            MODE=alsa_output.platform-hdmi-sound.stereo-fallback
                            LC_ALL=C pactl set-default-sink "${MODE}" || exit 1
                            ;;
                        "s922x")
                            if [[ "$BOARD" == "ogu" ]]; then
                                LC_ALL=C pactl set-default-sink INTERNAL
                                amixer -c 0 -q sset "Master" 100%
                                amixer -c 0 sset 'Playback Mux' SPK
                                amixer -c 0 -q sset 'FRDDR_A SINK 1 SEL' 'OUT 1'
                                amixer -c 0 -q sset 'FRDDR_A SRC 1 EN' 'on'
                            fi
                            ;;
                        "rk3326")
                            LC_ALL=C pactl set-default-sink INTERNAL
                            amixer -c 0 cset name='Playback Path' SPK
                            ;;
                        *)
                            # do nothing!
                            ;;
                    esac
                fi
                ;;
            *)
                LC_ALL=C pactl set-default-sink "${MODE}" || exit 1
                if [[ $(LC_ALL=C pactl get-default-sink) != "${MODE}" ]]; then
                    # default-sink didn't switch right away for some reason, try again later
                    exit 1
                fi
                ;;
        esac
        ;;

    list-profiles)
        printf "auto\tauto\n"
        LC_ALL=C pactl list cards-profiles-raw | grep 'available="1"' | sed -E 's/^card="[0-9]+" name="(.*)" profile="(.*)" available="[01]" active="[01]" description="(.*)"$/\2@\1\t\3/'
        ;;

    get-profile)
        /usr/bin/batocera-settings-get audio.profile
        ;;

    set-profile)
        MODE="$2"
        if [[ "${MODE}" != "auto" ]]; then
            if batocera-audio list-profiles | grep -q "${MODE}"; then
                PROFILE_NAME=$(echo "${MODE}" | cut -d '@' -f 1)
                CARD_NAME=$(echo "${MODE}" | cut -d '@' -f 2)
                LC_ALL=C pactl set-card-profile "${CARD_NAME}" "${PROFILE_NAME}" || exit 1
            else
                # the profile isn't available yet, try again later
                exit 1
            fi
        fi
        ;;

    getSystemVolume)
        echo "${DETECT_VOLUME}"
        ;;

    getSystemMute)
	    LC_ALL=C pactl get-sink-mute @DEFAULT_SINK@ | sed 's/.*: *\(.*\)/\1/' || exit 1
        ;;

    setSystemVolume)
        VOLUME="$2"
        case "${VOLUME}" in
            "mute")
                LC_ALL=C pactl set-sink-mute @DEFAULT_SINK@ 1 || exit 1
                ;;
            "unmute")
                LC_ALL=C pactl set-sink-mute @DEFAULT_SINK@ 0 || exit 1
                ;;
            "mute-toggle")
                LC_ALL=C pactl set-sink-mute @DEFAULT_SINK@ toggle || exit 1
                ;;
            *)
                if echo "${VOLUME}" | grep -qE '^[0-9]+$'; then
                    if [[ "${VOLUME}" -ge 0 && "${VOLUME}" -le "${MAX_VOLUME}" ]]; then
                        LC_ALL=C pactl set-sink-volume @DEFAULT_SINK@ "${VOLUME}%" || exit 1
                        exit 0
                    fi
                elif echo "${VOLUME}" | grep -qE '^[+-][0-9]+$'; then
                    let NEW_VOLUME=${DETECT_VOLUME}${VOLUME}
                    NEW_VOLUME=$(( NEW_VOLUME < 0 ? 0 : (NEW_VOLUME > MAX_VOLUME ? MAX_VOLUME : NEW_VOLUME) ))
                    LC_ALL=C pactl set-sink-volume @DEFAULT_SINK@ "${NEW_VOLUME}%" || exit 1
                    exit 0
                fi
                echo "invalid volume value" >&2
                exit 1
                ;;
        esac
        ;;

    test)
        aplay "/usr/share/sounds/Mallet.wav" || exit 1
        ;;
    *)
        do_usage "$(basename "$0")"
esac
